const mongoose = require("mongoose");
const rp = require("request-promise")
//新增店铺
const add = async (stores) => {
    const storesSchema = mongoose.model("shop-stores");
    return await storesSchema.create(stores)
}
//获取店铺列表
const get = async ({ curPage, eachPage }) => {
    const result = {
        curPage: ~~curPage,
        eachPage: ~~eachPage,
        total: 0,
        maxPage: 0,
        rows: []
    };
    const storesSchema = mongoose.model("shop-stores")
    //获取总条数
    result.total = await storesSchema.countDocuments()
    //获取最大页数
    result.maxPage = Math.ceil(result.total / result.eachPage)
    //链式调用  查询
    result.rows = await storesSchema
        //操作类型
        .find()
        //忽略条数
        .skip((result.curPage - 1) * result.eachPage)
        //显示多少条
        .limit(result.eachPage)
        //排序
        .sort({
            _id: -1
        })
        //执行execute
        .exec();
    return result;
};
//修改店铺信息
const editStores = async (storesMsg) =>
    await mongoose.model('shop-stores')
        .findByIdAndUpdate(storesMsg._id, {
            name: storesMsg.name,
            address: storesMsg.address,
            tel: storesMsg.tel,
            business: storesMsg.business,
            time: storesMsg.time,
            status: storesMsg.status,
            hasDistribution: storesMsg.hasDistribution,
        }, (err, ret) => {
            data = err ? console.log("失败", err) : console.log('成功');
        });
//删除店铺
const deleteStores = async ({ _id } = {}) =>
    await mongoose.model('shop-stores').deleteOne({ _id }, (err, ret) => {
        if (err) {
            console.log("删除失败");
        } else {
            console.log("删除成功");
        }
    })
//查询店铺
const searchStores = async (data) => {
    const { name = "", address = "",  curpage , eachpage  } = data;
    console.log( "接口服务器",name, address, curpage,eachpage);
    const result = {
        curpage: ~~curpage,
        eachpage: ~~eachpage,
        total: 0,
        maxpage: 0,
        rows: [],
    }
   

    result.rows = await mongoose.model('shop-stores').find(
        {
            name: {
                $regex: String(name)
            },
            address: {
                $regex: String(address)
            },
        }
    )
    result.total = result.rows.length;

    result.rows = await mongoose.model('shop-stores').find(
        {
            name: {
                $regex: String(name)
            },
            address: {
                $regex: String(address)
            },
        }
    ).skip((result.curpage - 1) * result.eachpage)
    .limit(result.eachpage)
    //排序
    .sort({
        _id: -1
    })
    .exec()
    result.maxpage = Math.ceil(~~result.total / result.eachpage);
    return result
}


module.exports = { add, get, editStores, deleteStores ,searchStores}